from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
# 这里使用相对导入路径会报错
from apps.teachers.models import Teacher
from apps.users.serializers import CreateUserSerializer, UserDetailSerializer, UpdateUserBaseInfoSerializer, \
    UpdateUserPasswordSerializer
from apps.users.authentication import CustomAuthentication
from apps.users.permissions import CustomIsAuthenticated
# MultiPartParser: 用于解析 multipart/form-data 类型的请求，这种类型通常用于上传文件
# FormParser: 用于解析 application/x-www-form-urlencoded 类型的请求，这种类型通常用于提交表单数据
from rest_framework.parsers import MultiPartParser, FormParser


# Create your views here.
class RegisterAPIView(GenericAPIView):
    queryset = Teacher.objects.all()
    serializer_class = CreateUserSerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"message": "登录成功!", **serializer.data}, status=status.HTTP_201_CREATED)


class LoginAPIView(APIView):

    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")

        if not all([username, password]):
            return Response({"message": "请提供完整的用户名和密码！"}, status=status.HTTP_400_BAD_REQUEST)

        user = Teacher.objects.filter(username=username).first()
        if user is None or not user.check_password(password):
            return Response({"message": "用户名或密码错误！"}, status=status.HTTP_400_BAD_REQUEST)

        if not user.is_active:
            return Response({"message": "您的账户未激活, 请联系管理员激活！"}, status=status.HTTP_400_BAD_REQUEST)

        token = user.generate_user_token()
        return Response({"message": "登录成功!", "token": token}, status.HTTP_200_OK)


class UserViewSet(ViewSet):
    authentication_classes = [CustomAuthentication]
    permission_classes = [CustomIsAuthenticated]

    def get_one(self, request):
        # Django内置的AuthenticationMiddleware中间件内部调用get_user函数将经过身份认证的对象绑定到request的user属性上
        serializer = UserDetailSerializer(request.user)
        return Response({"message": "获取用户详情信息成功!", "data": serializer.data}, status.HTTP_200_OK)

    def update_baseinfo(self, request):
        serializer = UpdateUserBaseInfoSerializer(instance=request.user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "用户基本信息更新成功!", "data": serializer.data}, status=status.HTTP_201_CREATED)

        return Response({"message": "参数错误!", "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

    def update_password(self, request):
        serializer = UpdateUserPasswordSerializer(instance=request.user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "更新密码成功!"}, status=status.HTTP_201_CREATED)
        return Response({"message": "更新密码失败!", "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

    def update_avatar(self, request):
        # MultiPartParser, FormParser 不能设置为全局解析类，其他视图为applications/json数据
        self.parser_classes = [MultiPartParser, FormParser]
        avatar_file = request.FILES.get('avatar')
        if avatar_file:
            request.user.avatar = avatar_file
            request.user.save()
            return Response({"message": "更新头像成功!"}, status=status.HTTP_201_CREATED)
        return Response({"message": "更新头像失败!", "errors": "未提供头像文件!"}, status=status.HTTP_400_BAD_REQUEST)